package patterns;

import java.util.Arrays;

/**
 * 缓存实例到数组中，同样实例则返回已有对象，没有则添加，数组满则往前移，加到最后*
 */

public class ArrayCacheImmutale {
    static class Immutable{
        private String name;
        public Immutable(String value){
            name = value;
        }

        @Override
        public boolean equals(Object obj){
            if (this == obj) return true;
            if (obj != null && obj.getClass() == Immutable.class){
                Immutable im = (Immutable) obj;
                return im.name.equals(name);
            }
            return false;
        }

        @Override
        public int hashCode(){
            return name.hashCode();

        }

        @Override
        public String toString(){
            return name;
        }

    }
    
    private static final int MAX_SIZE = 3;
    private static Immutable [] cacheImmutale = new Immutable[MAX_SIZE];
    private static int pos = 0;
    
    public static Immutable valueOf(String value){
        //loop array and find if exist value
        for (int i=0; i<pos; i++){
            if (value.equals(cacheImmutale[i].toString())){
                return cacheImmutale[i];
            } 
        }
        //can't find, add one
        if (pos == MAX_SIZE){
            //满了，把数组往前移一位，插在末尾
            System.out.println("before:" + Arrays.toString(cacheImmutale));
            System.arraycopy(cacheImmutale, 1, cacheImmutale, 0, MAX_SIZE-1);
            cacheImmutale[pos-1] = new Immutable(value);
            System.out.println("after:" + Arrays.toString(cacheImmutale));
        }else{
            cacheImmutale[pos] = new Immutable(value);
            pos++;
        }
        System.out.println("pos: " + pos);
        return cacheImmutale[pos-1];
    }
    
    public static void main(String arsg[]){
        Immutable it = ArrayCacheImmutale.valueOf("hello");
        Immutable itt = ArrayCacheImmutale.valueOf("hello9");
        Immutable it2 = ArrayCacheImmutale.valueOf("hello9");
        Immutable it3 = ArrayCacheImmutale.valueOf("hello9");
        Immutable it4 = ArrayCacheImmutale.valueOf("hello0");
        Immutable it5 = ArrayCacheImmutale.valueOf("hello2");
        System.out.println(it == itt);
        System.out.println(Arrays.toString(ArrayCacheImmutale.cacheImmutale));
    }
}
